﻿using DaqCollectionClient.Core;
using DaqCollectionClient.Model;
using System.ComponentModel;
using System.Windows;
using System.Windows.Forms;
using Tools;

namespace DaqCollectionClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        internal MainWindowViewModel viewModel { get; set; }

        /// <summary>
        /// 文件监控类
        /// </summary>
        internal FileMonitor fileMonitor { get; set; } = new FileMonitor();

        public MainWindow()
        {
            InitializeComponent();
            DataContext = viewModel = new MainWindowViewModel();
        }

        //protected override void OnClosing(CancelEventArgs e)
        //{
        //    this.Hide();
        //    e.Cancel = true;
        //}

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartBtn_Click(object sender, RoutedEventArgs e)
        {
            fileMonitor.Start(viewModel.MonitorFullPath, AgentFileChangedEvent, viewModel.Wildcard);
            OutPutLog("启动成功");
            StartBtn.IsEnabled = false;
            StopBtn.IsEnabled = true;
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            fileMonitor.Stop();
            OutPutLog("停止成功");
            StartBtn.IsEnabled = true;
            StopBtn.IsEnabled = false;
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectFolder_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                DialogResult result = dialog.ShowDialog();
                viewModel.MonitorFullPath = dialog.SelectedPath;
            }
        }

        /// <summary>
        /// 输出日志
        /// </summary>
        /// <param name="msg"></param>
        private void OutPutLog(string msg)
        {
            msgtxt.Dispatcher.Invoke(() =>
            {
                msgtxt.AppendText(msg);
                msgtxt.AppendText("\r\n");
                msgtxt.ScrollToEnd();
            });
        }

        /// <summary>
        /// 监控文件结果
        /// </summary>
        /// <param name="fileFullPath"></param>
        private void AgentFileChangedEvent(string fileFullPath)
        {
            OutPutLog($"监控到新文件：{fileFullPath}");
            new DataUploading(fileFullPath, viewModel.ServerAddr, OutPutLog);
        }
    }
}